//
//  MessageViewController.m
//  SXH
//
//  Created by 房 国生 on 15/8/26.
//  Copyright (c) 2015年 lyss. All rights reserved.
//

#import "MessageViewController.h"
#import "MessageTableViewCell.h"
#import "WebViewController.h"

#import "HMSegmentedControl.h"
#import "MJRefresh.h"
#import "MessageEntity.h"
#import "CommonService.h"
#import "UIView+AutoLayout.h"
@interface MessageViewController () {
    MJRefreshHeaderView *_header;
    MJRefreshFooterView *_footer;
    
    int pageUser;
    int pageSys;
    int showType;
}

@property (nonatomic, strong) IBOutlet UITableView *tableViewMessage;
@property (nonatomic, strong) NSMutableArray *mutableArrayMessage;
@property (nonatomic, strong) NSMutableArray *mutableArraySysMessage;
@property (nonatomic, strong) NSMutableArray *mutableArrayMessageType;;

@end

#define K_userMsg    @"用户消息"
#define K_systemMsg   @"系统消息"

#define K_cellIdentifier  @"MessageTableViewCell"


@implementation MessageViewController

@synthesize tableViewMessage, mutableArrayMessage, mutableArraySysMessage;
@synthesize mutableArrayMessageType;

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    showType = 0;
    pageUser = 1;
    pageSys = 1;
    mutableArrayMessage = [[NSMutableArray alloc] init];
    mutableArraySysMessage = [[NSMutableArray alloc] init];
    
    NSString *path=[[NSBundle mainBundle] pathForResource:@"MessageType" ofType:@"plist"];
    mutableArrayMessageType = [[NSMutableArray alloc] initWithContentsOfFile:path];
    
    HMSegmentedControl *segmentedControl2 = [[HMSegmentedControl alloc] initWithSectionTitles:@[K_userMsg, K_systemMsg]];
    [segmentedControl2 setIndexChangeBlock:^(NSUInteger index) {
        if (index == 0) {
            showType = (int)index;
            [self getMessageData:pageUser Path:USER_INBOX RefreshView:nil];
        } else if (index == 1) {
            showType = (int)index;
            [self getMessageData:pageUser Path:SYS_INBOX RefreshView:nil];
        }
        NSLog(@"Selected index %lu (via block)", (unsigned long)index);
    }];
    
    [segmentedControl2 setSelectionIndicatorHeight:2.0f];
    [segmentedControl2 setBackgroundColor:[UIColor whiteColor]];
    [segmentedControl2 setTextColor:[UIColor darkGrayColor]];
    [segmentedControl2 setSelectionIndicatorColor:[UIColor colorWithRed:0.55 green:0.77 blue:0.2 alpha:1]];
    [segmentedControl2 setSelectionIndicatorMode:HMSelectionIndicatorFillsSegment];
    [segmentedControl2 setSegmentEdgeInset:UIEdgeInsetsMake(0, 6, 0, 6)];
    [segmentedControl2 setCenter:CGPointMake(160, 120)];
    [segmentedControl2 setTag:2];
    segmentedControl2.frame = CGRectMake(SCREEN_WIDTH*0.125, 64, SCREEN_WIDTH*0.8, 45);
    
    [self.view addSubview:segmentedControl2];
    
    [self addHeader];
    [self addFooter];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    if (showType == 0) {
        return [mutableArrayMessage count];
    } else {
        return [mutableArraySysMessage count];
    }
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *couponTableViewCellIdentifier = K_cellIdentifier;
    MessageTableViewCell *cell = (MessageTableViewCell *)[tableView dequeueReusableCellWithIdentifier:couponTableViewCellIdentifier];
    if (cell == nil) {
        NSArray *array = [[NSBundle mainBundle] loadNibNamed:K_cellIdentifier owner:self options:nil];
        cell = [array objectAtIndex:0];
    }
    
    MessageEntity *entity = nil;
    if (showType == 0) {
        entity = [mutableArrayMessage objectAtIndex:indexPath.row];
    } else {
        entity = [mutableArraySysMessage objectAtIndex:indexPath.row];
    }
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *date = [dateFormatter dateFromString:entity.send_time];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];
    NSString *strDate = [dateFormatter stringFromDate:date];
    cell.labelTime.text = strDate;
    
    MCTopAligningLabel *labelTitle = [[MCTopAligningLabel alloc] initWithFrame:CGRectMake(58, 8, 247, 46)];
    [labelTitle setText:entity.message_text];
    labelTitle.font = [UIFont systemFontOfSize:14];
    labelTitle.textColor = [UIColor darkGrayColor];
    [cell addSubview:labelTitle];
    
    for (int i = 0; i < [mutableArrayMessageType count]; i++) {
        NSDictionary *dicMesageType = [mutableArrayMessageType objectAtIndex:i];
        NSString *type_id = [dicMesageType valueForKeyPath:@"id"];
        
        if ([entity.message_type isEqualToString:type_id] == YES) {
            NSString *name = [dicMesageType valueForKeyPath:@"name"];
            NSString *icon = [dicMesageType valueForKeyPath:@"icon"];
            
            cell.labelType.text = name;
            cell.imageViewIcon.image = [UIImage imageNamed:icon];
            
            break;
        }
    }
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 75;
}

#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    MessageEntity *entity = nil;
    if (showType == 0) {
        entity = [mutableArrayMessage objectAtIndex:indexPath.row];
    } else {
        entity = [mutableArraySysMessage objectAtIndex:indexPath.row];
    }
    if ([entity.message_type isEqualToString:@"1"] == YES ) {
        WebViewController *vc = [[WebViewController alloc] init];
        vc.url = entity.url;
        vc.vcTitle = entity.message_title;
        vc.imageShare = [UIImage imageNamed:@"icon-05 3"];
        [self.navigationController pushViewController:vc animated:YES];
    }
}

- (void) getMessageData:(int) pageNo
                   Path:(NSString *)path
            RefreshView:(MJRefreshBaseView *)refreshView {
    
    NSString *strPageNo = [NSString stringWithFormat:@"%d", pageNo];
    UserEntity *userEntity = [UserEntity sharedInstance];
    CommonService *service = [[CommonService alloc] init];
    NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:
                           strPageNo, @"page",
                           @"20", @"limit",
                           userEntity.userId,@"receiver_id",nil];
    
    [service getNetWorkData:param
                       Path:path
                  Successed:^(id entity) {
                      NSDictionary *dic = (NSDictionary *)entity;
                      NSArray *array = [dic objectForKey:@"rows"];
                      if (array.count > 0) {
                          [mutableArraySysMessage removeAllObjects];
                      }
                      for (NSDictionary* attributes in array) {
                          MessageEntity *entity = [[MessageEntity alloc] init];
                          entity = [entity initWithAttributes:attributes];
                          
                          if (showType == 0) {
                              [mutableArrayMessage addObject:entity];
                          }
                          else {
                              [mutableArraySysMessage addObject:entity];
                          }
                      }
                      [self doneWithView:refreshView];
                  } Failed:^(NSInteger errorCode, NSString *message) {
                      [self doneWithView:refreshView];
                  }];
}

- (void)addFooter {
    //__unsafe_unretained OAAnnoViewController *vc = self;
    MJRefreshFooterView *footer = [MJRefreshFooterView footer];
    footer.scrollView = self.tableViewMessage;
    footer.beginRefreshingBlock = ^(MJRefreshBaseView *refreshView) {
        if (showType == 0) {
            pageUser++;
            [self getMessageData:pageUser Path:USER_INBOX RefreshView:refreshView];
        } else {
            pageSys++;
            [self getMessageData:pageSys Path:SYS_INBOX RefreshView:refreshView];
        }
        NSLog(@"%@----开始进入刷新状态", refreshView.class);
    };
    _footer = footer;
}

- (void)addHeader {
    //__unsafe_unretained OAAnnoViewController *vc = self;
    MJRefreshHeaderView *header = [MJRefreshHeaderView header];
    header.scrollView = self.tableViewMessage;
    header.beginRefreshingBlock = ^(MJRefreshBaseView *refreshView) {
        // 进入刷新状态就会回调这个Block
        if (showType == 0) {
            [mutableArrayMessage removeAllObjects];
            [self getMessageData:1 Path:USER_INBOX RefreshView:refreshView];
        } else {
            [self getMessageData:1 Path:SYS_INBOX RefreshView:refreshView];
        }
        NSLog(@"%@----开始进入刷新状态", refreshView.class);
    };
    header.endStateChangeBlock = ^(MJRefreshBaseView *refreshView) {
        // 刷新完毕就会回调这个Block
        NSLog(@"%@----刷新完毕", refreshView.class);
    };
    header.refreshStateChangeBlock = ^(MJRefreshBaseView *refreshView, MJRefreshState state) {
        // 控件的刷新状态切换了就会调用这个block
        switch (state) {
            case MJRefreshStateNormal:
                NSLog(@"%@----切换到：普通状态", refreshView.class);
                break;
            case MJRefreshStatePulling:
                NSLog(@"%@----切换到：松开即可刷新的状态", refreshView.class);
                break;
            case MJRefreshStateRefreshing:
                NSLog(@"%@----切换到：正在刷新状态", refreshView.class);
                break;
            default:
                break;
        }
    };
    [header beginRefreshing];
    _header = header;
}

- (void)doneWithView:(MJRefreshBaseView *)refreshView {
    // 刷新表格
    [self.tableViewMessage reloadData];
    // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
    [refreshView endRefreshing];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:@"MessageViewController"];
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:@"MessageViewController"];
}


@end